#include "gtsort.h"

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

errno_t sort(
	void *base, \
	size_t num, \
	size_t size, \
	int(*comp)(const void*, const void*, void*), \
	void *ctx)
{
	if (base == NULL || num == 0 \
		|| size == 0 || comp == NULL)
		return 0;

	void *key = malloc(size);
	if (key == NULL)
		return ERROR_MEM_ALLOC;

	for (size_t i, j = 1; j < num; ++j)
	{
		memcpy(key, address(base, j, size), size);
		i = j - 1;
		while (true)
		{
			if (comp(address(base, i, size), key, ctx) <= 0)
			{
				memcpy(address(base, i + 1, size), key, size);
				break;
			}
			memcpy(address(base, i + 1, size), \
				address(base, i, size), size);

			if (i == 0)
			{
				memcpy(address(base, i, size), key, size);
				break;
			}
			--i;
		}
	}
	free(key);
	return 0;
}
